package myschool;

import com.google.gson.Gson;
import redis.clients.jedis.Jedis;

public class SubjectService {

    SubjectDao subjectDao = new SubjectDaoImpl();

    Jedis jedis = new Jedis("localhost",6379);

    Gson gson = new Gson();

    public Subject getOne(int subjectNo){
        String key = "sno"+subjectNo;
        Subject subject = null;
        //检查redis是否包含数据
        if(jedis.exists(key)){
            //如果有，直接读取redis
            subject = gson.fromJson(jedis.get(key),Subject.class);
            //重新设置过期时间
            jedis.expire(key,10*60);
        }else{
            //如果没有，读取mysql，并存入redis
            subject = subjectDao.getOne(subjectNo);
            jedis.setex(key,10*60,gson.toJson(subject));
        }
        return subject;
    }
}
